package logic

import (
	"face-revive-task/entity/config"
	"face-revive-task/repo"
	"fmt"
	"io"
	"os"
	"os/exec"
	"path/filepath"
)
import log "github.com/sirupsen/logrus"

func Do() {
	records, err := repo.QryWaiting()
	if err != nil {
		log.Errorf("qry waiting error %s", err)
	}
	for _, record := range records {
		log.Infof("start process %d,path %s", record.Id, record.Src)
		download, err := repo.Download(config.DownloadUrl, record.Src, config.DownloadDir, config.Token)
		if err != nil {
			log.Errorf("download id[%d] error %s", record.Id, err)
			continue
		}
		formerDst := execCodeFormer(download)
		err = handleResult(formerDst, record)
		if err != nil {
			log.Errorf("process %d,error %s", record.Id, err)
		}
	}
}

func handleResult(formerDst string, record *repo.RecordPO) error {
	// 处理失败
	if formerDst == "" {
		if err := repo.Update(record.Id, repo.Failed, ""); err != nil {
			log.Errorf("end process %d error %s", record.Id, err)
			return err
		}
		return fmt.Errorf("codeformer not create file")
	}
	_, err := os.Stat(formerDst)
	if os.IsNotExist(err) {
		if err := repo.Update(record.Id, repo.Failed, ""); err != nil {
			log.Errorf("end process %d error %s", record.Id, err)
			return err
		}
		return fmt.Errorf("codeformer create not exsit file")
	}
	// 上传
	relativePath, err := repo.Upload(formerDst, config.UploadUrl, config.Token)
	if err != nil {
		if err := repo.Update(record.Id, repo.Failed, ""); err != nil {
			log.Errorf("end process %d error %s", record.Id, err)
			return err
		}
		return err
	}
	if err := repo.Update(record.Id, repo.Success, relativePath); err != nil {
		log.Errorf("end process %d error %s", record.Id, err)
		return err
	}
	return nil
}

func execCodeFormer(src string) string {
	// python3 inference_codeformer.py -w 0.7 --input_path [image folder]|[image path]
	args := []string{"inference_codeformer.py", "-w", "0.7", "--input_path", src}
	cmd := exec.Command("python3", args...)
	// 获取标准输出和标准错误
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		log.Errorf("StdoutPipe Error %s", err)
		return ""
	}

	stderr, err := cmd.StderrPipe()
	if err != nil {
		log.Errorf("StderrPipe Error %s", err)
		return ""
	}

	// 启动命令
	if err := cmd.Start(); err != nil {
		log.Errorf("Start Error %s", err)
		return ""
	}

	// 读取标准输出
	stdoutBytes, err := io.ReadAll(stdout)
	if err != nil {
		log.Errorf("stdout Error:", err)
		return ""
	}

	// 读取标准错误
	stderrBytes, err := io.ReadAll(stderr)
	if err != nil {
		log.Errorf("stderr Error %s", err)
		return ""
	}

	// 等待命令完成
	if err := cmd.Wait(); err != nil {
		log.Errorf("Wait Error %s", err)
		return ""
	}
	// 打印输出
	log.Infof("stdout: %s", string(stdoutBytes))
	log.Infof("stdout: %s", string(stderrBytes))
	return "results/test_img_0.7/final_results/" + filepath.Base(src)
}
